package core

import (
	"GinBlog/global"
	"GinBlog/initialize"
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func RunServer() {

	Router := initialize.Routers()
	//TODO 端口需要走配置项
	address := ":8787"

	initServer(address, Router, 10*time.Minute, 10*time.Minute)

}

func initServer(address string, router *gin.Engine, duration time.Duration, duration2 time.Duration) {
	srv := &http.Server{
		Addr:           address,
		Handler:        router,
		ReadTimeout:    duration,
		WriteTimeout:   duration2,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			fmt.Printf("listen： %s\n", err)
			panic(err)
			os.Exit(1)
		}
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	global.Logger.Info("关闭WEB服务")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		global.Logger.Info("WEB服务关闭异常 Server Shutdown", zap.Error(err))
		os.Exit(1)
	}
}
